package com.tmp.alarm.utils;

/**
 * alarm demo for java（中文字符做json编码前要先Unicode编码）
 */
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * 发送告警信息
 */
public class SendMessagesUtils {

    private  final  static Logger LOGGER = LoggerFactory.getLogger(SendMessagesUtils.class);

    public static void main(String args[]) throws UnsupportedEncodingException
    {
        HashMap<String, String> alarmParams = new HashMap<String, String>();
        HashMap<String, String> alarmData = new HashMap<String, String>();
        /**
         * 发送短信告警
         */

        //13406425573;13870332129;15659868399
		alarmData.put("alarm_list","13466426673;");
		alarmData.put("alarm_title","jd test messages");
		alarmData.put("alarm_content","jd alarm test mart is ok to your phone");
		String dataStr =hashMapToJson(alarmData);

		// alarm post parameters
		alarmParams.put("app_name","mart_mobile_alarm");
		alarmParams.put("alarm_type","sms");
		alarmParams.put("data",dataStr);

		String param = hashMapToJson(alarmParams).replace("data\":\"{", "data\":{").replace("\"}\"}","\"}}");
		// 京东服务器环境上报URL
		System.out.println(param);

        param = java.net.URLEncoder.encode(param,"UTF-8");
		String url = "http://域名/tools/new_alarm_api/send_alarm?req=";

		String result = sendUrl(url,param);
		System.out.println(result);


        /**
         * 发送邮件告警
         */
		/*
    }


    /**
     * 发送手机短信消息
     * @param alarm_list  手机号码列表
     * @param alarm_title 发送标题
     * @param alarm_content 发送内容
     * @return 返回1则发送成功,返回0表示发送失败
     */
    public static String sendMessagesToPhone(String alarm_list,String alarm_title,String alarm_content){

        HashMap<String, String> alarmParams = new HashMap<String, String>();
        HashMap<String, String> alarmData = new HashMap<String, String>();
        /**
         * 发送短信告警
         */
        alarmData.put("alarm_list",alarm_list);
        alarmData.put("alarm_title",alarm_title);
        alarmData.put("alarm_content",alarm_content);
        String dataStr = hashMapToJson(alarmData);

        // alarm post parameters
        alarmParams.put("app_name","mart_mobile_alarm");
        alarmParams.put("alarm_type","sms");
        alarmParams.put("data",dataStr);

        String param = hashMapToJson(alarmParams).replace("data\":\"{", "data\":{").replace("\"}\"","\"}");
        // 服务器环境上报URL
        LOGGER.info(param);
        try {
            param = URLEncoder.encode(param,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = "http://域名/tools/new_alarm_api/send_alarm?req=";
        LOGGER.info("发送短信:"+param);
        String result = sendUrl(url,param);
        LOGGER.info("发送短信返回结果为:"+result);
        JSONObject jo = JSONObject.fromObject(result);
        String flag = "1";
        if(jo.get("status").equals("failure")){
            flag = "0";
        }
        return  flag;
    }



    /**
     * 把数据源HashMap转换成json
     * @param map
     */
    public static String hashMapToJson(HashMap map) {
        String string = "{";
        for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
            Entry e = (Entry) it.next();
            string += "\"" + e.getKey() + "\":";
            if(isNumeric((String) e.getValue())){

                string +=  e.getValue() + ",";
            }else{
                string += "\"" + e.getValue() + "\",";
            }
        }
        string = string.substring(0, string.lastIndexOf(","));
        string += "}";
        return string;
    }

    /**
     * 判断数字
     * @param str
     */
    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 把数据源String转换成Unicode编码
     * @param string
     */
    public static String string2Unicode(String string) {
        StringBuffer unicode = new StringBuffer();
        for (int i = 0; i < string.length(); i++) {
            char c = string.charAt(i);
            unicode.append("\\u" + Integer.toHexString(c));
        }
        return unicode.toString();
    }

    /**
     * 发送带参数的GET请求
     */
    private static String sendUrl(String url,String param) {
        String result = "";
        try{
            String urlName = url + param;
            URL urlObject = new URL(urlName);
            URLConnection connection = urlObject.openConnection();
            connection.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine())!= null){
                result += line;
            }
            in.close();
        }catch(Exception e){
            LOGGER.error("发送短信没有结果!"+e.getMessage());
        }
        return result;
    }

    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

}
